import { asyncRouterMap, constantRouterMap } from '@/router/index';

//判断是否有权限访问该菜单
function hasPermission(menus, route) {
  if (route.name) {
    let currMenu = getMenu(route.name, menus);
    if (currMenu != null) {
      //设置菜单的标题、图标和可见性
      if (currMenu.title != null && currMenu.title !== '') {
        route.meta.title = currMenu.title;
      }
      if (currMenu.icon != null && currMenu.title !== '') {
        route.meta.icon = currMenu.icon;
      }
      if (currMenu.hidden != null) {
        route.hidden = currMenu.hidden !== 0;
      }
      if (currMenu.sort != null && currMenu.sort !== '') {
        route.sort = currMenu.sort;
      }
      return true;
    } else {
      route.sort = 0;
      if (route.hidden !== undefined && route.hidden === true) {
        route.sort = -1;
        return true;
      } else {
        return false;
      }
    }
  } else {
    return false
  }
}

//根据路由名称获取菜单
function getMenu(name, menus) {
  for (let i = 0; i < menus.length; i++) {
    let menu = menus[i];
    if (name === menu) {
      return menu;
    }
  }
  return null;
}

//对菜单进行排序
function sortRouters(accessedRouters) {
  for (let i = 0; i < accessedRouters.length; i++) {
    let router = accessedRouters[i];
    if (router.children && router.children.length > 0) {
      router.children.sort(compare("sort"));
    }
  }
  accessedRouters.sort(compare("sort"));
}

//降序比较函数
function compare(p) {
  return function (m, n) {
    let a = m[p];
    let b = n[p];
    return b - a;
  }
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menus } = data;
        const { username } = data;
        const { user } = data;
        const { noMenus } = data;

        // 调试输出
        console.log('=== 菜单权限调试信息 ===');
        console.log('用户:', username);
        console.log('是否老板:', user.is_boss);
        console.log('可用菜单:', menus);
        console.log('禁用菜单:', noMenus);

        let accessedRouters = asyncRouterMap.filter(v => {
          console.log('检查路由:', v.name);

          if (getMenu(v.name, noMenus)) {
            console.log('  - 在禁用列表中，跳过');
            return false;
          }
          if (user.is_boss == 1) {
            console.log('  - 老板账号，通过');
            return true; //老板帐号直接返回所有菜单
          }

          let pnode = false;
          let num = 0;
          if (v.children && v.children.length > 0) {
            console.log('  - 有子菜单，开始检查子菜单');
            v.children = v.children.filter(child => {
              console.log('    检查子菜单:', child.name);
              if (hasPermission(menus, child)) {
                console.log('      - 子菜单有权限');
                if (child.hidden !== undefined && child.hidden === true) {
                  num++;
                }
                pnode = true; // 只要有子菜单通过权限检查，就显示父菜单
                return child
              }
              console.log('      - 子菜单无权限');
              return false;
            });
            console.log('  - 过滤后子菜单数量:', v.children.length, 'pnode:', pnode);
          }
          if (v.children && num == v.children.length) {
            pnode = false;
          }
          if (pnode || hasPermission(menus, v)) {
            console.log('  - 通过权限检查 (pnode:', pnode, ')');
            return v
          }
          // 修复：如果菜单在menus列表中，应该返回true
          if (getMenu(v.name, menus) != null) {
            console.log('  - 在菜单列表中，通过');
            return true;
          }
          console.log('  - 未通过权限检查');
          return false;
        });
        //对菜单进行排序
        sortRouters(accessedRouters);
        commit('SET_ROUTERS', accessedRouters);
        resolve();
      })
    }
  }
};

export default permission;
